<?php
class Payment_Refund 
{
    public function __construct ($orderId = NULL)
    {
        $this->_orderId = (int) $orderId;
    }

    public function detail ($id)
    {
        $query = DB::select()
            ->from('app_order_refund')
            ->where('id', '=', $id)
            ->execute();

        return $query->current();
    }

    public function add ($refundMoneyFen = NULL, $reason = NULL, $orderId = NULL)
    {
        $orderId = $orderId > 0 ? $orderId : $this->_orderId;
        $detail  = Order::detail($orderId);

        if (empty ($detail))
            return;

        $status = Arr::get($detail, 'status');
        if ($status != 4)
            return;

        $reason        = empty($reason) ? '订单退款' : trim($reason);

        $moneyTotalRMB = Arr::get($detail, 'moneyTotalRMB');
        $transId       = Arr::get($detail, 'transactionId');

        $trans         = new Payment_Transaction($transId);
        $payment       = $trans->detail();
        $platform      = Arr::get($payment, 'platform');
        $outTradeNo    = Arr::get($payment, 'out_trade_no');
        $transactionId = Arr::get($payment, 'transactionId');
        $totalFee      = Arr::get($payment, 'total_fee');
        $refundMoneyFen= $refundMoneyFen > 0 ? $refundMoneyFen : $moneyTotalRMB;
        $refundMoneyFen= $refundMoneyFen > $totalFee ? $totalFee : $refundMoneyFen;

        $row = array(
            'transactionId' => Arr::get($payment, 'transactionId'),
            'orderNo'       => Arr::get($detail, 'orderNo'),
            'orderId'       => $orderId,
            'totalMoney'    => $totalFee,
            'refundMoney'   => $refundMoneyFen,
            'created'       => DB::expr('unix_timestamp(now())'),
            'changed'       => DB::expr('unix_timestamp(now())'),
            'batchNo'       => '',
            'status'        => 0,
            'refundReason'  => $reason,
            'resultMessage' => '',
            'platform'      => $platform,
            'out_trade_no'  => $outTradeNo,
        );
        list($insert_id, $rows) = DB::insert('app_order_refund')
            ->columns (array_keys($row))
            ->values (array_values($row))
            ->execute();
    }

    public function getOrderIdFromTransactionId ($transId)
    {
        $orderId = DB::select('orderId')
            ->from('app_order_refund')
            ->where('transactionId', '=', $transId)
            ->execute()
            ->get('orderId');

        return $orderId;
    }

    public function setRefundSuccess($orderId)
    {
        if ($orderId <= 0)
            return;

        DB::update('app_order_refund')
            ->set(array(
                'status' => 1,
                'changed'       => DB::expr('unix_timestamp(now())'),
            ))
            ->where('orderId', '=', $orderId)
            ->execute();

        $order = new Order;
        $order->setOrderRefundSuccess($orderId);
    }
}
